<?php

jimport('joomla.application.component.controller');

class bgController extends JController {
     public function __construct(){
        parent::__construct();
        $this->model = $this->getModel(); 
        $this->aut = new bgAuthorize();
    }
    
    /**
	*Export data RESULT QUESTION to file csv
	*/
    public function export_csv(){
        $cid = JRequest::getVar('cid');
        if(HelperBG::export_csv_questionare($cid)){
                
                $this->setRedirect("index.php?option=com_questionare&task=summary&task=summary&cid=$cid");
        }
        else{
            JError::raiseError(500, 'Error ! Can\t export file CSV');
        }
        parent::display();
    }
    
    /**
     * Remove image when change file
    **/
    public function removeImage(){
        $image_name = JRequest::getVar('image_name');
        if($image_name != null){
            $path = "uploads/images/com_questionare/$image_name";
            if(file_exists($path)){
                $del = unlink($path);
            }
        }
        
        $app = &JFactory::getApplication();
        $app->close();
    }
    
    /**
     * COPY 
    */
    public function copy(){
        $cid = &JRequest::getVar('cid');
        
        if($cid != null){
            $cid = $cid[0];
            
            /* Load data from SERQ_CODE */
            $serq_item = $this->model->loadSerq($cid);
            $pagq_list = $this->model->loadPagqFromSerq($cid);
            $ques_list = $this->model->loadQuesFromSerq($cid);
            //create data for serq
            $serq_code_new = HelperBG::getIDAuto('serq','SERQ_CODE',20);
            $serq_item->SERQ_CODE = $serq_code_new*1;
            //set status publish: 0
            $serq_item->SERQ_PUBLISHED = 0;
            
            /* set value SERQ_IMG and copy IMG */
            if($serq_item->SERQ_IMG != null){
                $img_old = $serq_item->SERQ_IMG;
                $img = explode(".",$img_old);
                $extend = $img[count($img)-1];
                $path_source = "uploads/images/com_questionare/".$img_old;
                $img_new = 'se'.$serq_item->SERQ_CODE.'_'.date("Y-m-d_H-i",time()).'.'.$extend;
                $path_dest = "uploads/images/com_questionare/".$img_new;          
                if(file_exists($path_source)){
                    if(copy($path_source,$path_dest)){
                        $serq_item->SERQ_IMG = $img_new;
                    }
                }
            }
                      
            //create data for pagq
            $pagq_code_new = HelperBG::getIDAuto('pagq','PAGQ_CODE',10);
            $pagq_code = $pagq_code_new*1;
            
            
            for($i = 0; $i < count($pagq_list); $i++){
                               
                /* set lai gia tri cho PAGQ_CODE,PAGQ_SERQ_CODE */
                if($i == 0){
                    $pagq_code_old = $pagq_list[$i]->PAGQ_CODE;
                    $pagq_list[$i]->PAGQ_CODE = $pagq_code;
                }else{
                    $pagq_code++;
                    $pagq_code_old = $pagq_list[$i]->PAGQ_CODE;
                    $pagq_list[$i]->PAGQ_CODE = $pagq_code;
                }
                $pagq_list[$i]->PAGQ_SERQ_CODE = $serq_code_new;
                
                /* set lai gia tri cho QUES_PAGQ_CODE */
                for($j = 0; $j < count($ques_list); $j++){
                    if($ques_list[$j]->QUES_PAGQ_CODE == $pagq_code_old){
                        $ques_list[$j]->QUES_PAGQ_CODE = $pagq_code;
                    }
                }
                
                /* set value PAGQ_IMG and copy IMG */
                if($pagq_list[$i]->PAGQ_IMG != null){
                    $img_old = $pagq_list[$i]->PAGQ_IMG;
                    $img = explode(".",$img_old);
                    $extend = $img[count($img)-1];
                    $path_source = "uploads/images/com_questionpage/".$img_old;
                    $img_new = 'se'.$pagq_list[$i]->PAGQ_CODE.'_'.date("Y-m-d_H-i",time()).'.'.$extend;
                    $path_dest = "uploads/images/com_questionpage/".$img_new;          
                    if(file_exists($path_source)){
                        if(copy($path_source,$path_dest)){
                            $pagq_list[$i]->PAGQ_IMG = $img_new;
                        }
                    }
                }
                
            }
            
            //create data for question
            $ques_code_new = HelperBG::getIDAuto('ques','QUES_CODE',10);
            $ques_code = $ques_code_new*1;
            //$ques_list[0]->QUES_CODE = $ques_code;
            for($i = 0; $i < count($ques_list); $i++){
                /* set lai gia tri cho QUES_CODE,QUES_SERQ_CODE */
                if($i == 0){
                    $ques_code_old = $ques_list[$i]->QUES_CODE;
                    $ques_list[$i]->QUES_CODE = $ques_code;
                }else{
                    $ques_code++;
                    $ques_code_old = $ques_list[$i]->QUES_CODE;
                    $ques_list[$i]->QUES_CODE = $ques_code;
                }
                $ques_list[$i]->QUES_SERQ_CODE = $serq_code_new;
                
                /* load list ansq from ques_code old */
                $ansq_list = $this->model->loadAnsqFromQues($ques_code_old);
                
                /* kiem tra de loai bo truong hop cau hoi dang 3 - textbox */
                if($ansq_list != null){
                    $ansq_code_new = HelperBG::getIDAuto('ansq','ANSQ_CODE',10);
                    $ansq_code = $ansq_code_new*1;
                    /* set lai gia tri cho ANSQ_QUES_CODE */
                    for($j = 0; $j < count($ansq_list); $j++){
                        if($j == 0){
                            $ansq_code_old = $ansq_list[$j]->ANSQ_CODE;
                            $ansq_list[$j]->ANSQ_CODE = $ansq_code;
                        }else{
                            $ansq_code++;
                            $ansq_code_old = $ansq_list[$j]->ANSQ_CODE;
                            $ansq_list[$j]->ANSQ_CODE = $ansq_code;
                        }
                        
                        $ansq_list[$j]->ANSQ_QUES_CODE = $ques_code;
                    }
                    
                    /* save ansq */
                    $this->model->copyansq($ansq_list);
                    
                }
            }
            
            /* save data */
            if($serq_item != null){
                $this->model->copyserq($serq_item);
            }
            if($pagq_list != null){
                $this->model->copypagq($pagq_list);
            }
            if($ques_list != null){
                $this->model->copyques($ques_list);
            }
     
        }
         
        parent::display();
    }
    
    /* save */
    public function save(){
        $data = &JRequest::getVar('jform');
        
        /* check addnew or edit */
        if($this->getModel()->checkExistID($data['SERQ_CODE'])){
            $addNew = false;
        }else{
            $addNew = true;
        }
        if(empty($data['SERQ_TITLE'])){
                    $error = "アンケート名を選択してください。";
                    JRequest::setVar('task','error');
                    JFactory::getApplication()->enqueueMessage($error, 'error');
        }elseif(empty($data['SERQ_SEND_USER_ID_LIST'])){
                    $error = "配信先を入力してください。";
                    JRequest::setVar('task','error');
                    JFactory::getApplication()->enqueueMessage($error, 'error');
        }elseif(empty($data['SERQ_START'])){
                    $error = "開始を入力してください。";
                    JRequest::setVar('task','error');
                    JFactory::getApplication()->enqueueMessage($error, 'error');
        }elseif(empty($data['SERQ_FINISH'])){
                    $error = "完了を入力してください。";
                    JRequest::setVar('task','error');
                    JFactory::getApplication()->enqueueMessage($error, 'error');
        }elseif($data['SERQ_PUBLISHED']=="-1"){
                    $error = "フロントページを入力してください。";
                    JRequest::setVar('task','error');
                    JFactory::getApplication()->enqueueMessage($error, 'error');
        }else{
            /* get user current */
            $data['SERQ_USER_CREATE'] = $this->aut->getUserID();
            $data['SERQ_FLAG'] = '1';
            
           /* get image name */
            if($addNew == true){
                if($data['SERQ_IMG_NEW'] != null){
                    $data['SERQ_IMG'] = $data['SERQ_IMG_NEW'];                  
                }
            } else {
                if($data['SERQ_IMG_NEW'] != null){
                        $data['SERQ_IMG'] = $data['SERQ_IMG_NEW'];
                        
                } else {
                    if($data['IMG_OLD'] != null){
                        $data['SERQ_IMG'] = $data['IMG_OLD'];
                    }
                }
            } 
         
            /* save data */  
            if($this->model->save($data, $addNew)){
                //del old file
                if($data['SERQ_IMG_NEW'] != null){
                    if($data['SERQ_IMG_NEW'] != $data['IMG_OLD']){
                        $path = "uploads/images/com_questionare/".$data['IMG_OLD'];
                        if(file_exists($path)){ 
                            $del = unlink($path);
                        }
                    }
                }
                
                $this->setRedirect('index.php?option=com_questionare');
            }else{
                //JError::raiseError(500, 'Error ! Can\'t save questionare' );
                //$error = "Error! Can't save!";
                $error = "エラー！データが記録されません。";
                JRequest::setVar('task','');
                JFactory::getApplication()->enqueueMessage($error, 'error');
            }
        }
        parent::display();
    }
    
     
     /* savetemp */
    public function savetemp(){
        $data = &JRequest::getVar('jform');
        
        /* check addnew or edit */
        if($this->getModel()->checkExistID($data['SERQ_CODE'])){
            $addNew = false;
        }else{
            $addNew = true;
        }
        if(empty($data['SERQ_TITLE'])){
                    $error = "アンケート名を入力してください。";
                    JRequest::setVar('task','error');
                    JFactory::getApplication()->enqueueMessage($error, 'error');
        }elseif(empty($data['SERQ_SEND_USER_ID_LIST'])){
                    $error = "配信先を入力してください。";
                    JRequest::setVar('task','error');
                    JFactory::getApplication()->enqueueMessage($error, 'error');
        }elseif(empty($data['SERQ_START'])){
                    $error = "開始を入力してください。";
                    JRequest::setVar('task','error');
                    JFactory::getApplication()->enqueueMessage($error, 'error');
        }elseif(empty($data['SERQ_FINISH'])){
                    $error = "完了を入力してください。";
                    JRequest::setVar('task','error');
                    JFactory::getApplication()->enqueueMessage($error, 'error');
        }elseif($data['SERQ_PUBLISHED']=="-1"){
                    $error = "フロントページを入力してください。";
                    JRequest::setVar('task','error');
                    JFactory::getApplication()->enqueueMessage($error, 'error');
        }else{ 
            /* get user current */
            $data['SERQ_USER_CREATE'] = $this->aut->getUserID();
            /* save temp */
            $data['SERQ_FLAG'] = '0';
            
           /* get image name */
            if($addNew == true){
                if($data['SERQ_IMG_NEW'] != null){
                    $data['SERQ_IMG'] = $data['SERQ_IMG_NEW'];                  
                }
            } else {
                if($data['SERQ_IMG_NEW'] != null){
                        $data['SERQ_IMG'] = $data['SERQ_IMG_NEW'];
                        
                } else {
                    if($data['IMG_OLD'] != null){
                        $data['SERQ_IMG'] = $data['IMG_OLD'];
                    }
                }
            } 
          
            /* save data */  
            if($this->model->save($data, $addNew)){
                //del old file
                if($data['SERQ_IMG_NEW'] != null){
                    if($data['SERQ_IMG_NEW'] != $data['IMG_OLD']){
                        $path = "uploads/images/com_questionare/".$data['IMG_OLD'];
                        if(file_exists($path)){ 
                            $del = unlink($path);
                        }
                    }
                }
                
                $this->setRedirect('index.php?option=com_questionare');
            }else{
                //JError::raiseError(500, 'Error ! Can\'t save questionare' );
                //$error = "Error! Can't save!";
                $error = "エラー！データが記録されません。";
                JRequest::setVar('task','');
                JFactory::getApplication()->enqueueMessage($error, 'error');
            }
        }
        parent::display();
    } 
    /* remove questionare items */
    public function remove(){
    	$cid = JRequest::getVar('cid');  
        
        /* remove image in server */
        foreach($cid as $value){
            //get image name
            $img = $this->getModel()->getImgFromSERQ_CODE($value);
            //Del Image
            if($img != null){
                
                if($img->SERQ_IMG != null){
                    $path = "uploads/images/com_questionare/$img->SERQ_IMG";
                    if(file_exists($path)){
                        $del = unlink($path);
                    }
                }
                
            }
        }
        $this->model->remove($cid);
        
        /* REMOVE PAGQ */
        
        foreach($cid as $value){
            //get image name
            $img = $this->model->getImgFromPAGQ_CODE($value);
            //Del Image
            if($img != null){
                
                if($img->PAGQ_IMG != null){
                    $path = "uploads/images/com_questionpage/$img->PAGQ_IMG";
                    if(file_exists($path)){
                        $del = unlink($path);
                    }
                }
                
            }
        }     
        $this->model->removepagq($cid);
        
        /* REMOVE ANSQ */
        
        if($cid != null){
            $arr_quescode = array();
            for($i = 0; $i < count($cid); $i++){
                $ques_list = $this->model->loadQuesFromSerq($cid[$i]);
                foreach($ques_list as $value){
                    $arr_quescode[] = $value->QUES_CODE;
                }
                
            }
        }
        
        $this->model->removeansq($arr_quescode);
        
        /* remove ques */
        $this->model->removeques($cid);
        
        /*  REMOVE RESQ*/
        $this->model->removeresq($cid);

        /*  REMOVE SESS*/
        $this->model->removesess($cid);
        
        $this->setRedirect('index.php?option=com_questionare'); 
    }
    
    
    /* pop up */
    public function selectArea(){
        $area_code = JRequest::getCmd('area_code',0);
        
        $model = $this->getModel();
        $pref = $model->getAllPrefOfArea($area_code);
        echo '<select name="pref" id="pref" class="medium">';
        echo '<option value="0" selected="selected">全て...</option>"';                             
        foreach($pref as $value){                       
            echo '<option value="'.$value->PREF_CODE.'">'.$value->PREF_NAME.'</option>';        
        }                       
        echo '</select>';
        $app = &JFactory::getApplication();
        $app->close();
        exit();
    }
    
    public function search_user(){
        $filter = array(
            'ocba_name' => JRequest::getVar('ocba_name'),
            'pref_search' => JRequest::getVar('pref_search'),
            'area_search' => JRequest::getVar('area_search'),
            'usertype_search' => JRequest::getVar('usertype_search'),
            );
        $result = $this->getModel()->getAllUserMail($filter);
        
        echo '<div class="the_scroll">
                      <table>
                         <thead>
                            <tr>
                                <th class="check"><input id="toggle" name="toggle" type="checkbox" onclick="checkAll(this);checkID();" /></th>
                                <th class="code"> 配信先コード</th>
                                <th class="mail"> 配信先名</th>
                            </tr>
                         </thead>
                         
                         <tbody>';
        if(!empty($result)){
            foreach ($result as $key => $row){
                echo   '<tr>
                           <td class="check">
                                <input class="checkbox-id" type="checkbox" id="cb'.$row->id.'" name="cid[]" value="'.$row->id.'" onclick="isChecked(this.checked);checkID('.$row->id.');" />                           
                           </td>
                            <td class=" code" id="user'.$row->id.'">'.$row->id.'</td>
                           <td class="" id="email'.$row->id.'">'.$row->name.'</td>
                        </tr>';
            }
        } else {
            echo   '    <tr>
                            <td class="left" colspan="3">データは見つかりませんでした。</td>
                        </tr>';
        }
        
        echo '          </tbody>         
                    </table>
                      </div>
                      <input type="hidden" id="all_user" name="all_user" value="'.$s.'" />
                      <input type="hidden" name="task" value="" />
                      <input type="hidden" name="boxchecked" id="boxchecked" value="0"/>
                      
                      <textarea name="list_uid" id="list_uid"></textarea>
                      ';
        
        $app = &JFactory::getApplication();
        $app->close();
    }

}